// api/post.go
package api

import (
	"errors"
	"haiqiu-blog-go/common"
	"haiqiu-blog-go/dao"
	"haiqiu-blog-go/models"
	"haiqiu-blog-go/service"
	"haiqiu-blog-go/utils"
	"net/http"
	"strconv"
	"strings"
	"time"
)

func (*Api) SaveAndUpdatePost(w http.ResponseWriter, r *http.Request) {
	token := r.Header.Get("Authorization")
	if token == "" {
		common.Error(w, errors.New("未登录"))
		return
	}
	_, claims, err := utils.ParseToken(token)
	if err != nil {
		common.Error(w, errors.New("登录已过期"))
		return
	}
	uid := claims.Uid
	// post 请求保存
	method := r.Method
	switch method {
	case http.MethodPost:
		params := common.GetRequestJsonParam(r)
		cId := params["categoryId"].(string)
		categoryId, _ := strconv.Atoi(cId)
		content := params["content"].(string)
		markdown := params["markdown"].(string)
		slug := params["slug"].(string)
		title := params["title"].(string)
		var pType int
		//if params["type"] != nil || params["type"] != "" {
		//	postType := params["type"].(float64)
		//	pType = int(postType)
		//}

		post := &models.Post{
			-1,
			title,
			slug,
			content,
			markdown,
			categoryId,
			uid,
			0,
			pType,
			time.Now(),
			time.Now(),
		}
		service.SavePost(post)
		common.Success(w, post)
	case http.MethodPut:
		// update
		params := common.GetRequestJsonParam(r)
		cId := params["categoryId"].(string)
		categoryId, _ := strconv.Atoi(cId)
		content := params["content"].(string)
		markdown := params["markdown"].(string)
		slug := params["slug"].(string)
		title := params["title"].(string)
		postType := params["type"].(float64)
		pidFloat := params["pid"].(float64)
		pType := int(postType)
		pid := int(pidFloat)
		post := &models.Post{
			pid,
			title,
			slug,
			content,
			markdown,
			categoryId,
			uid,
			0,
			pType,
			time.Now(),
			time.Now(),
		}
		service.UpdatePost(post)
		common.Success(w, post)
	}
}

func (*Api) GetPost(w http.ResponseWriter, r *http.Request) {
	path := r.URL.Path
	postIdStr := strings.TrimPrefix(path, "/api/v1/post/")
	postId, err := strconv.Atoi(postIdStr)
	if err != nil {
		common.Error(w, errors.New("文章ID解析失败"))
		return
	}
	post, err := dao.GetPostDetailById(postId)
	if err != nil {
		common.Error(w, errors.New("文章获取失败"))
		return
	}
	if post == nil {
		common.Error(w, errors.New("文章不存在或被删除"))
	}
	common.Success(w, post)
}

func (*Api) Login(w http.ResponseWriter, r *http.Request) {
	//接收用户名和密码 返回 对应的json数据
	params := common.GetRequestJsonParam(r)
	userName := params["username"].(string)
	passwd := params["passwd"].(string)
	loginRes, err := service.Login(userName, passwd)
	if err != nil {
		common.Error(w, err)
		return
	}
	common.Success(w, loginRes)
}

func (*Api) SearchPost(w http.ResponseWriter, r *http.Request) {
	err := r.ParseForm()
	if err != nil {
		common.Error(w, errors.New("解析参数错误"))
	}
	condition := r.Form.Get("val")
	searchResps := service.SearchPost(condition)
	common.Success(w, searchResps)
}
